"""
 Retrieves a specific post from Blogger in HTML.
 This service relies on Google GData.
 
 @example /srv/s2/blog-id/post-id/
 
 @author Jean-Lou Dupont
"""
import os
import sys
import types
import re
import wsgiref.handlers
from google.appengine.ext           import webapp
#from google.appengine.ext.webapp    import template
from libs.wiki import template
from google.appengine.api           import urlfetch


import urllib # Used to unescape URL parameters.
from gdata import service
import gdata
import atom
import gdata.urlfetch
# Use urlfetch instead of httplib
gdata.service.http_request_handler = gdata.urlfetch

class Service_S2( webapp.RequestHandler ):
    """
    My second WEB-Service with AppEngine
    """

    def __init__(self):
        self.p = re.compile("(.+)post-(.*)$")

    def get(self, blog_id, post_id ):
    
        feed = self.getPosts(blog_id)
        if ( feed == 0 ):
            return

        for entry in feed.entry:
            id = entry.id.text
            title = entry.title.text
            content = entry.content.text
            
            if self.findPost(entry, post_id, id) == 1:
                self.printPost(title, content)
                break
 
    def getPosts(self, blog_id ):
        blogger_service = service.GDataService( )
        blogger_service.source = 'service #2'
        blogger_service.service = 'blogger'
        blogger_service.server = 'www.blogger.com'

        feed = 0;
        try:
            feed = blogger_service.GetFeed('/feeds/' + blog_id + '/posts/default')
        except:
            pass
        
        return feed
 

    def findPost(self, entry, post_id, search ):
        m = self.p.match( search )
        found = 0
        if ( type(m) <> types.NoneType ):
            rid = m.group(2)
            if ( post_id == rid ):
                found = 1
        return found

    def printPost(self, title, content ):
        template_values = { 'title': title , 'content': content };
        
        # Path to the template
        path = os.path.join(os.path.dirname(__file__), 'template.html')
        
        # template replacement & rendering
        self.response.out.write(template.render(path, template_values))
        

#/**
# *  Initialize http handler
# */
def main():
  application = webapp.WSGIApplication([('/srv/s2/(.*?)/(.*)/', Service_S2)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

# Bootstrap
#  It all starts here
if __name__ == "__main__":
    main()